package org.projectname.service.admin.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hishenframework.core.data.jdbc.template.DataPaging;
import org.hishenframework.core.data.jdbc.template.JdbcOperater;
import org.projectname.entity.manager.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService extends JdbcOperater<User> {

	public int delete(int id) {
		String sql = "SELECT count(*) FROM t_system_user_role WHERE user_id = ?";
		long count = super.getJdbcTemplate().queryForLong(sql, id);
		return count == 0 ? super.delete(id) : 0;
	}

	public void search(DataPaging<User> dataPaging, String username, Date from,
			Date to) {
		StringBuilder sql = new StringBuilder(
				"SELECT * FROM t_system_user WHERE 1 = 1 ");
		List<Object> values = new ArrayList<>();
		if (username != null) {
			sql.append(" AND username = ? ");
			values.add(username);
		}
		if (from != null) {
			sql.append(" AND regist_date > ? ");
			values.add(from);
		}
		if (to != null) {
			sql.append(" AND regist_date < ? ");
			values.add(to);
		}
		query().qDataPaging(dataPaging, sql.toString(), values.toArray());
	}

	@Override
	public long save(User entity) {
		return super.save(entity);
	}

	@Override
	public int update(User entity) {
		if (isExsit(entity)) {
			return 0;
		}
		return super.update(entity);
	}

	public int updateUsername(User entity){
		if (isExsit(entity)) {
			return 0;
		}
		String username = entity.getUsername();
		entity = get(entity.getId());
		entity.setUsername(username);
		return super.update(entity);
	}
	
	public boolean isExsit(User entity) {
		StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM t_system_user WHERE username = ?");
		List<Object> values = new ArrayList<>();
		values.add(entity.getUsername());
		if(entity.getId() != null){
			sql.append(" AND id <> ?");
			values.add(entity.getId());
		}
		long count = getJdbcTemplate().queryForLong(sql.toString(), values.toArray());
		return count >= 1;
	}

}
